import { defineComponent, ref, onUnmounted, watchEffect, createVNode } from 'vue';
import { clamp } from './utils.js';

const Hue = /* @__PURE__ */ defineComponent({
  name: 'Hue',
  props: {
    value: {
      type: Object
    }
  },
  emits: ['change'],
  setup(props, {
    emit
  }) {
    const left = ref(clamp(props.value.hsl.h * 100 / 360, 0, 100));
    // const left = () => clamp(props.value.hsl.h * 100 / 360, 0, 100);
    let container;
    const handleMouseDown = e => {
      if (typeof e.button === 'number' && e.button !== 0) return false;
      handleChange(e);
      document.addEventListener('mousemove', handleChange, false);
      document.addEventListener('mouseup', onDragEnd, false);
    };
    const onDragEnd = e => {
      handleChange(e);
      document.removeEventListener('mousemove', handleChange);
      document.removeEventListener('mouseup', onDragEnd);
    };
    onUnmounted(() => {
      document.removeEventListener('mousemove', handleChange);
      document.removeEventListener('mouseup', onDragEnd);
    });
    const handleChange = e => {
      e.preventDefault();
      e.stopPropagation();
      const {
        clientWidth
      } = container;
      const xOffset = container.getBoundingClientRect().left + window.screenX;
      const left = e.clientX - xOffset;
      if (left < 0) {
        change(0);
        return;
      }
      if (left > clientWidth) {
        change(100);
        return;
      }
      change(left * 100 / clientWidth);
    };
    const change = percent => {
      left.value = clamp(percent, 0, 100);
      const {
        h,
        s,
        l,
        a
      } = props.value.hsl;
      const newHue = clamp(percent / 100 * 360, 0, 360);
      if (h !== newHue) {
        emit('change', {
          h: newHue,
          s,
          l,
          a,
          source: 'hsl'
        });
      }
    };
    watchEffect(() => {
      left.value = clamp(props.value.hsl.h * 100 / 360, 0, 100);
    });
    return () => createVNode("div", {
      "class": "cm-color-picker-hue",
      "ref": el => container = el
    }, [createVNode("div", {
      "class": "cm-color-picker-hue-wrap",
      "onMousedown": handleMouseDown
    }, [createVNode("div", {
      "class": "cm-color-picker-hue-pointer",
      "style": {
        top: 0,
        left: `${left.value}%`
      }
    }, null)])]);
  }
});

export { Hue };
